package org.code.mallspringboot.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.code.mallspringboot.dto.ConfirmOrderResult;
import org.code.mallspringboot.mapper.MemberMapper;
import org.code.mallspringboot.pojo.OmsCartItem;
import org.code.mallspringboot.pojo.UmsMemberReceiveAddress;
import org.code.mallspringboot.service.OmsCartItemService;
import org.code.mallspringboot.service.UmsMemberReceiveAddressService;
import org.code.mallspringboot.utils.JwtUtil;
import org.code.mallspringboot.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private OmsCartItemService omsCartItemService;

    @Autowired
    private UmsMemberReceiveAddressService umsMemberReceiveAddressService;

    /**
        去结算
        -商品信息
     * @param cartIds
     * @return
     */
    @PostMapping("/generateConfirmOrder")
    public CommonResult generateConfirmOrder(@RequestBody int[] cartIds, HttpServletRequest request){

        ConfirmOrderResult  confirmOrderResult = new ConfirmOrderResult();
        List<OmsCartItem> omsCartItemList = new ArrayList<>();
        for (int cartId : cartIds) {
            omsCartItemList.add(omsCartItemService.selectById(cartId));
        }
        List<UmsMemberReceiveAddress> memberReceiveAddressList = new ArrayList<>();
        // 从请求头中获取token
        String token = request.getHeader("authorization");
        token = token.replaceAll("Bearer", "");
        String userName = JwtUtil.getUserName(token);
        int memberId = memberMapper.member_id(userName);
        List<UmsMemberReceiveAddress> memberReceiveAddressList2 = umsMemberReceiveAddressService.selectByMemberId(memberId);
        for (UmsMemberReceiveAddress umsMemberReceiveAddress : memberReceiveAddressList2) {
            memberReceiveAddressList.add(umsMemberReceiveAddress);
        }

        confirmOrderResult.setCartPromotionItemList(omsCartItemList);
        confirmOrderResult.setMemberReceiveAddressList(memberReceiveAddressList);
        return CommonResult.success(confirmOrderResult);
    }
}
